class GameView extends ui.GameUI {
    // private mole: Mole
    private moles: Array<Mole>
    private moleNum: number = 9
    private score:number
    private hammer:Hammer

    constructor () {
        super()
        // this.mole = new Mole(this.normal, this.hit, 21)
        this.moles = new Array<Mole>()
        this.timeBar.value = 1
        this.score = 0
        var hitCallBackHd: Laya.Handler = Laya.Handler.create(this, this.setScore, null, false)
        for (var i = 0; i < this.moleNum; i++) {
            var box: Laya.Box = this.getChildByName('item' + i) as Laya.Box
            var mole: Mole = new Mole(
                box.getChildByName('normal') as Laya.Image,
                box.getChildByName('hit') as Laya.Image,
                box.getChildByName('scoreImg') as Laya.Image,
                21, hitCallBackHd)
            this.moles.push(mole)
        }
        // 创建事件循环
        this.hammer = new Hammer()
        this.hammer.visible = false
        this.addChild(this.hammer)
        this.gameStart()
    }
    private onLoop ():void {
        this.timeBar.value -= (1 / 10)
        if (this.timeBar.value <= 0) {
            // 游戏结束
            this.gameOver()
            return
        }
        var index:number = Math.floor(Math.random() * this.moleNum)
        this.moles[index].show()
    }
    public gameStart ():void {
        this.hammer.visible = true
        this.timeBar.value = 1
        this.score = 0
        this.updateScoreUI()
        Laya.timer.loop(1000, this, this.onLoop)
        this.hammer.start()
    }
    // 游戏结束
    private gameOver ():void {
        // 清除事件循环
        Laya.timer.clear(this, this.onLoop)
        this.hammer.visible = false
        this.hammer.end()
        if (!GameMain.gameOver) {
            GameMain.gameOver = new GameOver();
        }
        GameMain.gameOver.setScoreUI(this.score)
        GameMain.gameOver.centerX = 0
        GameMain.gameOver.centerY = 40
        this.stage.addChild(GameMain.gameOver)
        console.log('游戏结束！')
    }
    /**
     * @description 设置分数
     */
    private setScore (type: number):void {
        this.score += type === 1 ? -100 : 100
        if (this.score < 0) this.score = 0
        this.updateScoreUI()
    }

    private updateScoreUI () : void {
        var data:any = {}
        var temp:number = this.score
        for (var i:number = 9; i >= 0; i--) {
            data['item' + i] = {index: Math.floor(temp % 10)}
            temp /= 10
        }
        this.scoreNums.dataSource = data
    }
    
}